import {
  menuList
} from '@/service/api/sys.js'
import adminConfig from '@/admin.config.js'
import {
  cloneDeep
} from 'lodash'
import {
  useSysStore
} from '@/store/sys'

/**
 * 客户端获取菜单数据，并处理树状结构 - 弃用 议直接在客户端生成树状数据
 * @tutorial https://uniapp.dcloud.net.cn/uniCloud/jql.html#gettree
 * @param {Object} params 分页或筛选参数
 */
export async function buildMenu(params) {
  const menuRes = await menuList(params)
  const list = menuRes?.data || []
  const staticMenu = adminConfig.sideBar.staticMenu
  const flat = list.concat(staticMenu)
  return {
    dynamic: list,
    origin: flat,
    tree: buildTree(cloneDeep(flat)),
  }
}

/**
 * 服务端获取树状菜单数据
 * @tutorial https://uniapp.dcloud.net.cn/uniCloud/jql.html#gettree
 */
export async function getMenu() {
  // 获取当前用户权限
  const {
    role,
    permission
  } = uniCloud.getCurrentUserInfo()
  // 遍历角色，取出权限数组合并去重
  const menuRes = await menuList({
    role,
    permission
  })
  const list = menuRes?.data || []
  const staticMenu = adminConfig.sideBar.staticMenu
  const tree = list.concat(staticMenu)
  return {
    tree
  }
}

// 菜单树状数据构建 - 建议直接在服务端生成树状数据
function buildTree(items, parent_id = '') {
  let tree = []
  for (let i = 0; i < items.length; i++) {
    if (items[i].parent_id === parent_id) {
      let children = buildTree(items, items[i].menu_id)
      if (children.length > 0) {
        items[i].children = children
      }
      tree.push(items[i])
    }
  }
  return tree
}

// 菜单url检索
export function findUrlByMenuId(data, id) {
  let result = [];
  data.forEach(function(item) {
    if (item.menu_id === id) {
      result.push(item.url);
    } else if (item.children && item.children.length > 0) {
      let childResult = findUrlByMenuId(item.children, id);
      if (childResult) {
        result.push(childResult);
      }
    }
  });
  return result.length > 0 ? result[0] : null;
}

/**
 * 字典提取
 * @param {string} dict_id 字典id
 * @param {boolean} mapType 字典类型 true时转换为键值对，false时为数组形式
 */
export function getDictById(dict_id, mapType = false) {
  let result
  const sysStore = useSysStore()
  let localDicts = sysStore.getDicts()
  let findDict = localDicts.find(item => item.dict_id === dict_id)
  if (!findDict?.dict || findDict?.dict?.length <= 0) {
    uni.showToast({
      title: '字典读取有误，请尝试更新系统缓存',
      icon: 'none',
    })
    return
  }
  if (mapType) {
    result = handleMap(findDict.dict)
  } else {
    result = findDict.dict
  }
  return result
}

/**
 * 将标准数组转换为对象
 * @param {Object} arr 标准数组[{key:'a', value:'1'},{key:'b', value:'2'}...]
 * @return 对象{a:'1',b:'2',...}
 */
function handleMap(arr) {
  // return arr.reduce((acc, cur) => {
  //   acc[cur.key] = cur.value
  //   return acc
  // }, {})
  return Object.fromEntries(arr.map((obj) => [obj.key, obj.value]))
}

/**
 * 菜单守卫，校验菜单权限
 */
function menuRouter() {

}